package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.CheckSetupBean;
import com.ekuaitu.kuaitu.bean.DropOffCarBean;
import com.ekuaitu.kuaitu.bean.FenceData;
import com.ekuaitu.kuaitu.bean.OperateBean;
import com.ekuaitu.kuaitu.bean.OrderDetailBean;
import com.ekuaitu.kuaitu.map.MarkerUtils;
import com.ekuaitu.kuaitu.map.PolylineBoundUtils;
import com.ekuaitu.kuaitu.map.RoutePlanUtils;
import com.ekuaitu.kuaitu.map.SensorEventHelper;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.DensityUtils;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SetupDialog;
import com.ekuaitu.kuaitu.utils.SetupRemindDialog;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;

public class CarInUseActivity extends BaseActivity implements AMapLocationListener, AMap.OnMarkerClickListener {

    @BindView(R.id.hotLine_inUse)
    TextView hotLineInUse;
    @BindView(R.id.textView_inUse_time)
    TextView textViewInUseTime;
    @BindView(R.id.imageButton_inUse_lockOff)
    ImageButton imageButtonInUseLockOff;
    @BindView(R.id.imageButton_inUse_lockOn)
    ImageButton imageButtonInUseLockOn;
    @BindView(R.id.textView_inUse_dropOffCar)
    TextView tVInUseDropOffCar;
    @BindView(R.id.imageButton_inUse_findCar)
    ImageButton imageButtonInUseFindCar;
    @BindView(R.id.tv_inUse_license)
    TextView tvInUseLicense;
    @BindView(R.id.progress_bar_in_use)
    RelativeLayout progressBarInUse;
    @BindView(R.id.imageView_refresh)
    ImageView imageView_refresh;
    @BindView(R.id.imageView_all)
    ImageView imageView_all;
    @BindView(R.id.setup_inUse)
    ImageView setupInUse;
    @BindView(R.id.xd_layout)
    RelativeLayout xd_layout;

    private MapView mapView;
    private AMap aMap;
    private MarkerUtils markerUtils;
    private Marker locationMarker;
    private PolylineBoundUtils polylineBoundUtils;
    private SensorEventHelper mSensorHelper;
    private View infoWindow = null;

    private GeoFenceClient mGeoFenceClient;
    //定义接收广播的action字符串
    public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private static boolean isExit = false;
    private LatLng curPosition;
    private Context mContext = this;
    private String orderId;
    private String carId;
    private String carLicense;
    private String parkId;
    private String areaCode;
    private long count = 0;
    private int operateType = -1;
    private double carBonCoefficient;
    private TimerTask task;
    private Timer timer;
    private PowerManager.WakeLock wakeLock;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    count++;
                    if (count > 86400) {
                        textViewInUseTime.setText(getSpannableString(TimeUtils.formatMinPlusOne(count + "")));
                    } else {
                        textViewInUseTime.setText(TimeUtils.formatSecondCount(count + "", 1));
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private boolean isFirstLocation = true;

    @Override

    public int getLayoutId() {
        return R.layout.activity_car_in_use;
    }


    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        initWeilanClient();
        initMap();
        startLocation();
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        orderId = intent.getStringExtra(IntentKey.INTENT_ORDER_ID);
        getOrderDetail();
        boolean isHide = SharedPreferencesUtils.getInstance(this).getBooleanValue("notFirstComeIn");
        if (isHide) {
            xd_layout.setVisibility(View.GONE);
        } else {
            xd_layout.setVisibility(View.VISIBLE);
            SharedPreferencesUtils.getInstance(this).putBooleanValue("notFirstComeIn", true);
        }
        //汽车整备活动未开启时，不显示活动介绍入口
        int isShowCarPrepare = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_CAR_PREPARE);
        if (isShowCarPrepare == 1) {
            setupInUse.setVisibility(View.VISIBLE);
        } else {
            setupInUse.setVisibility(View.GONE);
        }
    }

    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(false);
            aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(final Marker marker) {
                    if (infoWindow == null) {
                        infoWindow = LayoutInflater.from(mContext).inflate(R.layout.car_red_info_window, null);
                    }
                    render(marker, infoWindow); //设置弹窗的内容
                    infoWindow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext, NaviActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("latitude", curPosition.latitude + "");
                            bundle.putString("longitude", curPosition.longitude + "");
                            bundle.putString("toLatitude", marker.getPosition().latitude + "");
                            bundle.putString("toLongitude", marker.getPosition().longitude + "");
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                    return infoWindow;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }

                public void render(Marker marker, View view) {
                    TextView tv_distance = (TextView) view.findViewById(R.id.info_window_name);
                    tv_distance.setText(marker.getTitle());
                }
            });// 设置自定义InfoWindow样式
            aMap.setMapType(AMap.MAP_TYPE_NAVI);
            //设置点击marker事件监听器
            aMap.setOnMarkerClickListener(this);
            UiSettings uiSettings = aMap.getUiSettings();
            //设置地图交互
            uiSettings.setMyLocationButtonEnabled(false);
            uiSettings.setScaleControlsEnabled(false);
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setZoomControlsEnabled(false);
            uiSettings.setScrollGesturesEnabled(true);
            uiSettings.setZoomGesturesEnabled(true);
            uiSettings.setTiltGesturesEnabled(false);

            //设置定位的参数
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mLocationClient.setLocationListener(this);
                //设置为高精度定位模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                mLocationOption.setInterval(2000);
                //设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
            }
            markerUtils = new MarkerUtils(mContext, aMap);
            polylineBoundUtils = new PolylineBoundUtils(aMap);

            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    //backPress(false);
                }
            });

            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {

                }

                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                }
            });
        }
    }

    @Override
    protected void initMapView(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(R.id.car_inuse_map);
        mapView.onCreate(savedInstanceState);
    }

    /**
     * 实例化地理围栏客户端
     */
    private void initWeilanClient() {
        mGeoFenceClient = new GeoFenceClient(getApplicationContext());
        mGeoFenceClient.setActivateAction(GEOFENCE_IN | GEOFENCE_OUT | GEOFENCE_STAYED);
        //创建并设置PendingIntent
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);

        //注册围栏广播
        IntentFilter fliter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        fliter.addAction(GEOFENCE_BROADCAST_ACTION);
        registerReceiver(mGeoFenceReceiver, fliter);
    }


    @OnClick({R.id.imageButton_inUse_lockOff, R.id.imageButton_inUse_lockOn, R.id.textView_inUse_dropOffCar, R.id.hotLine_inUse,
            R.id.imageButton_inUse_findCar, R.id.imageView_refresh, R.id.imageView_all, R.id.xd_layout, R.id.setup_inUse})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageButton_inUse_findCar:
                operateType = 2;
                progressBarInUse.setVisibility(View.VISIBLE);
                startLocation();
                break;
            case R.id.imageButton_inUse_lockOff:
                operateType = 0;
                progressBarInUse.setVisibility(View.VISIBLE);
                startLocation();
                break;
            case R.id.imageButton_inUse_lockOn:
                operateType = 1;
                progressBarInUse.setVisibility(View.VISIBLE);
                startLocation();
                break;
            case R.id.hotLine_inUse:
                final Intent intent2 = new Intent();
                View popupView = getLayoutInflater().inflate(R.layout.menu_inuse, null);
                final PopupWindow popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                popupWindow.showAsDropDown(findViewById(R.id.hotLine_inUse), -(int) DensityUtils.dp2px(mContext, 40), 0);
                popupView.findViewById(R.id.compliants_inuse).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        intent2.setClass(mContext, ComplaintsActivity.class);
                        intent2.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        intent2.putExtra(IntentKey.INTENT_TRIP_MODE, 1);
                        intent2.putExtra("licenseTag", carLicense);
                        startActivity(intent2);
                        popupWindow.dismiss();
                    }
                });

                popupView.findViewById(R.id.lin_hotLine_inuse).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final KuaituDialog kuaituDialog2 = new KuaituDialog(mContext);
                        kuaituDialog2.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog2.setMessage("是否拨打客服电话" + MyApplication.getInstance().getHotLine());
                        kuaituDialog2.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_DIAL);
                                intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                                startActivity(intent);
                                kuaituDialog2.dismiss();
                                popupWindow.dismiss();
                            }
                        });
                        kuaituDialog2.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog2.dismiss();
                                popupWindow.dismiss();
                            }
                        });
                        kuaituDialog2.show();
                    }
                });
                break;
            case R.id.textView_inUse_dropOffCar:
                final KuaituDialog kuaituDialog = new KuaituDialog(this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage(getResources().getString(R.string.dropOffCarRemind));
                kuaituDialog.setYesOnclickListener("还车", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        dropOffCar(orderId, carId, parkId);
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.show();
                break;
            case R.id.imageView_refresh:
                if (curPosition != null) {
                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)), 700, null);
                }
                break;
            case R.id.imageView_all:
                if (curPosition != null) {
                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 11, 0, 0)), 700, null);
                }
                break;
            case R.id.xd_layout:
                xd_layout.setVisibility(View.GONE);
                break;

            case R.id.setup_inUse:
                final SetupRemindDialog setupDialog = new SetupRemindDialog(mContext);
                setupDialog.setCloseOnclickListener(new SetupRemindDialog.onCloseOnclickListener() {
                    @Override
                    public void onCloseClick() {
                        setupDialog.dismiss();
                    }
                });
                setupDialog.show();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        initSensor();
    }

    private void getOrderDetail() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getOrderDetail(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<OrderDetailBean>() {
                    @Override
                    public void onResponse(Call<OrderDetailBean> call, Response<OrderDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                OrderDetailBean.AttachmentBean result = response.body().getAttachment();
                                carId = result.getCarModel().getId();
                                parkId = result.getCarModel().getParkId() + "";
                                carLicense = result.getCarModel().getLicenseTag();
                                tvInUseLicense.setText(carLicense);
                                Date date = new Date();
                                if (result.getStartBillingTime() <= 0) {
                                    count = 1;
                                } else {
                                    count = (int) ((date.getTime() - result.getStartBillingTime()) / 1000) + 1;
                                }
                                if (count < 0) {
                                    count = 1;
                                }
                                if (count > 86400) {
                                    textViewInUseTime.setText(getSpannableString(TimeUtils.formatMinPlusOne(count + "")));
                                } else {
                                    textViewInUseTime.setText(TimeUtils.formatSecondCount(count + "", 1));
                                }
                                carBonCoefficient = result.getCarbonEmissionCar();
                                countTime();
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OrderDetailBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    //是否享受车辆整备送优惠券活动
    private void hasSetupActivity() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).checkSetup(MyApplication.getInstance().getRequestFieldMap(), orderId).enqueue(new Callback<CheckSetupBean>() {
            @Override
            public void onResponse(Call<CheckSetupBean> call, final Response<CheckSetupBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    switch (response.body().getStatus()) {
                        case "200":
                            //享受资格
                            setupInUse.setVisibility(View.VISIBLE);
                            break;
                        case "400":
                            //不享受资格
                            setupInUse.setVisibility(View.GONE);
                            break;
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckSetupBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mLocationClient.startLocation();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final KuaituDialog kuaituDialog = new KuaituDialog(CarInUseActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("您已拒绝定位权限");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                        startLocation();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        progressBarInUse.setVisibility(View.GONE);
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();

            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    /**
     * 开车门 关车门 寻车后5秒内阻止用户点击
     */
    private void startProgress() {
        progressBarInUse.setVisibility(View.VISIBLE);
        new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                progressBarInUse.setVisibility(View.GONE);
            }
        }.start();
    }

    private void lockCarOn(final String orderId, final String carId, final String longitude, final String latitude) {
        progressBarInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).openCarDoor(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        startProgress();
                    } else if (response.body().getStatus() == 400) {
                        progressBarInUse.setVisibility(View.GONE);
                        final KuaituDialog kuaituDialog = new KuaituDialog(CarInUseActivity.this);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setMessage(getString(R.string.openCarDoorForce));
                        kuaituDialog.setYesOnclickListener("开门", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                progressBarInUse.setVisibility(View.VISIBLE);
                                ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).openCarDoor(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude, "1").enqueue(new Callback<OperateBean>() {
                                    @Override
                                    public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                                        if (response.isSuccessful() && response.body() != null) {
                                            if (response.body().getStatus() == 200) {
                                                progressBarInUse.setVisibility(View.GONE);
                                            } else {
                                                progressBarInUse.setVisibility(View.GONE);
                                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<OperateBean> call, Throwable t) {
                                        progressBarInUse.setVisibility(View.GONE);
                                        ToastCompat.makeText(mContext, getResources().getString(R.string.openCarDoorFailure), Toast.LENGTH_LONG).show();
                                    }
                                });
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.show();
                    } else {
                        progressBarInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                progressBarInUse.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.openCarDoorFailure), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void lockCarOff(final String orderId, final String carId, final String longitude, final String latitude) {
        progressBarInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).closeCarDoor(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude, "0").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        startProgress();
                    } else if (response.body().getStatus() == 401) {
                        progressBarInUse.setVisibility(View.GONE);
                        final KuaituDialog kuaituDialog = new KuaituDialog(CarInUseActivity.this);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setMessage(getString(R.string.closeCarDoorForce));
                        kuaituDialog.setYesOnclickListener("锁门", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                progressBarInUse.setVisibility(View.VISIBLE);
                                ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).closeCarDoor(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude, "1").enqueue(new Callback<OperateBean>() {
                                    @Override
                                    public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                                        if (response.isSuccessful() && response.body() != null) {
                                            if (response.body().getStatus() == 200) {
                                                progressBarInUse.setVisibility(View.GONE);
                                            } else {
                                                progressBarInUse.setVisibility(View.GONE);
                                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<OperateBean> call, Throwable t) {
                                        progressBarInUse.setVisibility(View.GONE);
                                    }
                                });
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog.dismiss();
                                progressBarInUse.setVisibility(View.GONE);
                            }
                        });
                        kuaituDialog.show();
                    } else {
                        progressBarInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                progressBarInUse.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.shutCarDoorFailure), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void dropOffCar(final String orderId, String carId, String parkId) {
        progressBarInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).dropOffCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, parkId).enqueue(new Callback<DropOffCarBean>() {
            @Override
            public void onResponse(Call<DropOffCarBean> call, Response<DropOffCarBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        IntentUtils.toSettlementActivity(CarInUseActivity.this, orderId, "");
                        finish();
                    } else {
                        progressBarInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<DropOffCarBean> call, Throwable t) {
                progressBarInUse.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.dropOffCarFailure), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void findCar(String orderId, String carId, String longitude, String latitude) {
        progressBarInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).findCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, longitude, latitude).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        startProgress();
                    } else {
                        progressBarInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                progressBarInUse.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.findCarFailure), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initSensor() {
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            mSensorHelper.registerSensorListener();
            if (mSensorHelper.getCurrentMarker() == null && locationMarker != null) {
                mSensorHelper.setCurrentMarker(locationMarker);
            }
        }
    }

    private SpannableString getSpannableString(String dateString) {
        SpannableString spannableString = new SpannableString(dateString);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("天"), dateString.indexOf("天") + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("小时"), dateString.indexOf("小时") + 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), dateString.indexOf("分钟"), dateString.indexOf("分钟") + 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private void countTime() {
        if (task == null) {
            task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendEmptyMessage(1);
                }
            };
        }
        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(task, 0, 1000); //延时0ms后执行，1000ms执行一次
        }
        acquireWakeLock();
    }


    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                mLocationClient.startLocation();
            }
        } else {
            mLocationClient.startLocation();
        }

    }

    /**
     * 路径规划
     *
     * @param tarPosition
     */
    private void routePlanning(LatLng tarPosition) {
        RoutePlanUtils.getInstance().startRoutePlanning(mContext, aMap, curPosition, tarPosition, false, null);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            if (isFirstLocation) {
                MyApplication.getInstance().setAreaCode(aMapLocation.getCityCode());
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)));
                locationMarker = markerUtils.addLocationIcon(curPosition);
                //mCircle = polylineBoundUtils.addCircle(curPosition, amapLocation.getAccuracy());//添加定位精度圆
                locationMarker.setClickable(false);
                mSensorHelper.setCurrentMarker(locationMarker);
                isFirstLocation = false;
                getFenceListData(curPosition.latitude + "", curPosition.longitude + "");
            }
            if (operateType == 0) {
                operateType = -1;
                progressBarInUse.setVisibility(View.GONE);
                lockCarOff(orderId, carId, aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "");
            } else if (operateType == 1) {
                operateType = -1;
                progressBarInUse.setVisibility(View.GONE);
                lockCarOn(orderId, carId, aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "");
            } else if (operateType == 2) {
                operateType = -1;
                progressBarInUse.setVisibility(View.GONE);
                findCar(orderId, carId, aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "");
            }
        } else {
            ToastCompat.makeText(mContext, "获取位置信息失败，请重试...", Toast.LENGTH_LONG).show();
        }
    }

    private void getFenceListData(String latitude, String longitude) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getFenceList(MyApplication.getInstance().getRequestFieldMap(), latitude, longitude).enqueue(new Callback<FenceData>() {
            @Override
            public void onResponse(Call<FenceData> call, Response<FenceData> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        FenceData.Attachment attachment = response.body().getAttachment();
                        if (attachment != null) {
                            List<FenceData.ParkFence> parkFenceList = attachment.getParkFenceList();
                            addBoundsToMap(parkFenceList);
                            addGeoFenceToMap(parkFenceList);
                            markerUtils.addRedCarMarkersToMap(aMap, parkFenceList);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<FenceData> call, Throwable t) {

            }
        });
    }

    public List<Polygon> addBoundsToMap(List<FenceData.ParkFence> geoFenceList) {
        List<Polygon> polygonList = new ArrayList<>();
        for (int i = 0; i < geoFenceList.size(); i++) {//每一个网点
            List<List<FenceData.ParkFence.FPoint>> weilanList = geoFenceList.get(i).getFenceList();
            for (int j = 0; j < weilanList.size(); j++) {
                polygonList.add(aMap.addPolygon(new PolygonOptions().addAll(createBound(weilanList.get(j))).fillColor(Color.parseColor("#33FA960A")).strokeColor(Color.parseColor("#FA960A")).strokeWidth(6)));
            }
        }
        return polygonList;
    }

    private List<LatLng> createBound(List<FenceData.ParkFence.FPoint> fencePoints) {
        List<LatLng> boundList = new ArrayList<>();
        for (int i = 0; i < fencePoints.size(); i++) {
            LatLng latLng = new LatLng(fencePoints.get(i).getLatitude(), fencePoints.get(i).getLongitude());
            boundList.add(latLng);
        }
        return boundList;
    }

    //向地图中加入电子围栏数据
    public void addGeoFenceToMap(List<FenceData.ParkFence> geoFenceList) {
        for (int i = 0; i < geoFenceList.size(); i++) {//每一个网点
            List<List<FenceData.ParkFence.FPoint>> weilanList = geoFenceList.get(i).getFenceList();
            for (int j = 0; j < weilanList.size(); j++) {//每一个围栏
                mGeoFenceClient.addGeoFence(createGeofenceInfos(weilanList.get(j)), "123456");
            }
        }
    }

    /**
     * 电子围栏数据
     *
     * @param fencePoints
     * @return
     */
    private List<DPoint> createGeofenceInfos(List<FenceData.ParkFence.FPoint> fencePoints) {
        List<DPoint> boundList = new ArrayList<>();
        for (int i = 0; i < fencePoints.size(); i++) {
            DPoint dPoint = new DPoint(fencePoints.get(i).getLatitude(), fencePoints.get(i).getLongitude());
            boundList.add(dPoint);
        }
        return boundList;
    }

    /**
     * 围栏广播监听
     */
    private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                //解析广播内容
                //获取Bundle
                Bundle bundle = intent.getExtras();
                //获取围栏行为：
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                //获取自定义的围栏标识：
                String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
                //获取围栏ID:
                String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
                //获取当前有触发的围栏对象：
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                switch (status) {
                    case GEOFENCE_IN:
                        Log.d("围栏广播监听", "进入了" + customId);
                        break;
                    case GEOFENCE_OUT:
                        Log.d("围栏广播监听", "出去了" + customId);
                        break;
                    case GEOFENCE_STAYED:
                        Log.d("围栏广播监听", "在围栏内停留了10分钟" + customId);
                        break;
                }
            }
        }
    };

    @Override
    public boolean onMarkerClick(Marker marker) {
        Map<String, String> markerInfo = (Map<String, String>) marker.getObject();
        //规划地图路径
        routePlanning(marker.getPosition());
        marker.setTitle(markerInfo.get("parkName"));
        //显示网点名称
        marker.showInfoWindow();
        return true;
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastCompat.makeText(this, "订单进行中，再按一次退出应用", Toast.LENGTH_LONG).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 3000);
        } else {
            releaseWakeLock();
            AppManager.getAppManager().AppExit(mContext);
        }
    }

    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }

    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
        unregisterReceiver(mGeoFenceReceiver);
    }


}
